﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Services.Description;
using Newtonsoft.Json;
using umbraco.presentation.plugins.tinymce3;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using UmbracoGuitarGreb.Models;
using UmbracoExamine.DataServices;

namespace UmbracoGuitarGreb.Controllers
{
    public class SongsApiController : UmbracoApiController
    {
        public string GetAllSongs()
        {
            var bands = new List<Band>();

            var service = Services.ContentService;

            var songs = Services.ContentService.GetContentOfContentType(GetContentType("Song").Id).Where(x => x.Published);

            var jsongs = JsonConvert.SerializeObject(songs);

            return JsonConvert.SerializeObject(songs);
        }

        public IEnumerable<Letter> GetLetters()
        {
            var service = Services.ContentService;

            var objLetters = new List<Letter>();

            var letters = Services.ContentService.GetContentOfContentType(GetContentType("Alfabet").Id).Where(x => x.Published).OrderBy(x => x.Name);

            foreach (var let in letters)
            {
                objLetters.Add(new Letter
                {
                    Id = let.Id,
                    Name = let.Name
                });
            }

            return objLetters;
        }

        public IEnumerable<Band> GetBandsByParent(int parentId)
        {
            var service = Services.ContentService;

            var objBands = new List<Band>();

            var bands = Services.ContentService.GetContentOfContentType(GetContentType("Band").Id).Where(x => x.Published && x.ParentId == parentId);

            foreach (var band in bands)
            {
                var tmpBand = new Band
                {
                    Id = band.Id,
                    Name = band.Name,
                    Songs = ConvertSongsToList(band.Children())
                };
                objBands.Add(tmpBand);
            }
            return objBands;
        }
        
        public string GetSongsByBandId(int bandId)
        {
            return "";
        }

        public string GetSongById(int songId)
        {
            return "";
        }

        private IContentType GetContentType(string alias)
        {
            return Services.ContentTypeService.GetContentType(alias);
        }

        private IEnumerable<Song> ConvertSongsToList(IEnumerable<IContent> songs)
        {
            return songs.Select(song => new Song
            {
                Id = song.Id,
                Name = song.Name,
                Text = song.GetValue<string>("bodyText")
            }).ToList();
        }
    }
}